import useTileLayer from './useTileLayer'
import * as ol from 'ol'
import 'ol/ol.css'
import useProjection from './useProjection'
import TileLayer from 'ol/layer/Tile'
import OSM from 'ol/source/OSM'
import useTifLayer from './useTifLayer'
import useLabellayer from './useLabellayer'
function useOlMap() {
    const { proj4326 } = useProjection()

    const view = new ol.View({
        center: [113.091931, 34.534477],
        zoom: 0,
        projection: proj4326?.getCode(),

        // projection: proj3857?.getCode(),
    })

    const map: ol.Map = new ol.Map({
        view,
        controls: [],
    })

    const {
        labelLayer,
    } = useLabellayer()

    function initMap(element: HTMLElement) {
        map.setTarget(element)
    }

    const { tileLayer } = useTileLayer()

    const osmLayer = new TileLayer({
        source: new OSM({
            wrapX: false,
        }),
    })

    function initTileLayer() {
        map.addLayer(tileLayer)
    }

    function flyTo(location, done) {
        const duration = 2000
        const zoom = view.getZoom() || 0
        let parts = 2
        let called = false
        function callback(complete) {
            --parts
            if (called) {
                return
            }
            if (parts === 0 || !complete) {
                called = true
                done(complete)
            }
        }
        view.animate(
            {
                center: location,
                duration: duration,
            },
            callback,
        )
        view.animate(
            {
                zoom: zoom - 1,
                duration: duration / 2,
            },
            {
                zoom: zoom,
                duration: duration / 2,
            },
            callback,
        )
    }

    return {
        map,
        initMap,
        initTileLayer,
        tileLayer,
        osmLayer,
        view,
        labelLayer,
    }
}

export default useOlMap
